import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref(localStorage.getItem('username') || '')

  const isLoggedIn = computed(() => !!token.value)

  const setUserInfo = (userToken, userUsername) => {
    token.value = userToken
    username.value = userUsername
    localStorage.setItem('token', userToken)
    localStorage.setItem('username', userUsername)
  }

  const clearUserInfo = () => {
    token.value = ''
    username.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('username')
  }

  const loginAction = async (loginData) => {
    try {
      const response = await login(loginData)
      console.log('Store login response:', response)
      
      if (response.data && response.data.code === 200) {
        const data = response.data.data
        if (data && data.token && data.username) {
          setUserInfo(data.token, data.username)
          return { success: true, message: '登录成功' }
        } else {
          return { success: false, message: '登录响应数据格式错误' }
        }
      } else {
        return { success: false, message: response.data?.message || '登录失败' }
      }
    } catch (error) {
      console.error('Store login error:', error)
      return { success: false, message: error.message || '登录失败' }
    }
  }

  const logout = () => {
    clearUserInfo()
  }

  return {
    token,
    username,
    isLoggedIn,
    setUserInfo,
    clearUserInfo,
    loginAction,
    logout
  }
}) 